<template>
  <!-- 实物盘点商品导入 -->
  <el-dialog
    v-model="visible"
    :modal="false"
    :title="$t('product.uploadTips')"
    :close-on-click-modal="false"
    class="component-take-stock-prod-upload"
    width="38%"
  >
    <div class="tips">
      <p>{{ $t('shop.exportProdTip1') }}</p>
      <p>{{ $t('takeStock.exportTip1') }}</p>
      <p>{{ $t('takeStock.exportTip') }}</p>
    </div>
    <div style="display: inline-block">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :action="http.adornUrl('/stock/takeStockProd/importExcel')"
        :headers="{ Authorization: cookie.get('bbcAuthorization_vs'),locale:lang }"
        :limit="1"
        name="excelFile"
        :data="{takeStockId: takeStockId}"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-error="uploadFalse"
        :on-success="uploadSuccess"
        :file-list="files"
        :auto-upload="false"
        :before-upload="beforeAvatarUpload"
      >
        <template #tip>
          <div

            class="el-upload__tip"
          />
        </template>
        <template #trigger>
          <div class="default-btn primary-btn">
            {{ $t("product.selectFile") }}
          </div>
        </template>
        <div
          v-if="isAuth('multishop:takeStockProd:import')"
          class="default-btn download-btn"
          @click="submitUpload"
        >
          {{ $t("product.import") }}
        </div>
        <div
          v-if="isAuth('multishop:takeStockProd:download')"
          class="default-btn download-btn"
          @click="downloadModel"
        >
          {{ $t("product.downloadTemplate") }}
        </div>
      </el-upload>
    </div>
  </el-dialog>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { isAuth } from '@/utils'
import http from '@/utils/http.js'
import cookie from 'vue-cookies'
const emit = defineEmits(['refreshDataList', 'refreshDataList'])

const lang = localStorage.getItem('bbcLang') || 'zh_CN'
const visible = ref(false)
let upload = false
let takeStockId = null
const files = ref([])

const uploadSuccess = (response) => {
  alert(response.data)
  files.value = []
  visible.value = false
  emit('refreshDataList')
}
const uploadFalse = (response) => {
  alert(response.data || $t('product.fileUploadFail'))
}
const init = (id) => {
  visible.value = true
  takeStockId = id
}
defineExpose({ init })
// 上传前对文件的大小的判断
const beforeAvatarUpload = (file) => {
  upload = true
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!extension && !extension2) {
    alert($t('product.downloadTemplateTips1'))
  }
  if (!isLt2M) {
    alert($t('product.downloadTemplateTips2'))
  }
  return extension || (extension2 && isLt2M)
}
const uploadRef = ref(null)
const submitUpload = () => {
  upload = false
  uploadRef.value?.submit()
  if (!upload) {
    ElMessage.error($t('shop.fileNullTip'))
  }
}
const handleRemove = () => {
}
const handlePreview = (file) => {
  if (file.response.status) {
    alert($t('product.fileSuccess'))
    emit('refreshDataList')
  } else {
    alert($t('product.fileFail'))
  }
}
// 下载模板
const downloadModel = () => {
  http({
    url: http.adornUrl('/stock/takeStockProd/downLoadModel'),
    method: 'get',
    responseType: 'blob' // 解决文件下载乱码问题
  }).then(({ data }) => {
    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
    const fileName = $t('takeStock.exportProdFileName')
    const elink = document.createElement('a')
    if ('download' in elink) { // 非IE下载
      elink.download = fileName
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      URL.revokeObjectURL(elink.href) // 释放URL 对象
      document.body.removeChild(elink)
    } else { // IE10+下载
      navigator.msSaveBlob(blob, fileName)
    }
  })
}

</script>
<style scoped>
.download-btn {
  margin-left: 12px;
}
div :deep(.el-dialog__body) {
  padding-top: 10px;
}
</style>
